package com.ssc.chain.tcfp.core.client;


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author mingjian
 * @version 1.0
 * Create by 2025/7/10 17:46
 */
public class LocalFileUploadStore implements UploadStore {

    private final Path baseDir;

    public LocalFileUploadStore(String baseDir) {
        this.baseDir = Paths.get(baseDir);
    }

    private Path getFilePath(String uploadId) {
        return baseDir.resolve(uploadId);
    }

    private Path getMetaFilePath(String uploadId) {
        return baseDir.resolve(uploadId + ".meta");
    }

    @Override
    public void createUpload(String uploadId, long length) throws IOException {
        Files.createDirectories(baseDir);
        Path file = getFilePath(uploadId);
        if (!Files.exists(file)) {
            Files.createFile(file);
        }
        // 写入元数据文件，保存文件总长度
        Path meta = getMetaFilePath(uploadId);
        try (BufferedWriter writer = Files.newBufferedWriter(meta)) {
            writer.write(Long.toString(length));
        }
    }

    @Override
    public void append(String uploadId, long offset, InputStream data, long length) throws IOException {
        Path file = getFilePath(uploadId);
        try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "rw")) {
            raf.seek(offset);
            byte[] buf = new byte[8192];
            long remain = length;
            int read;
            while (remain > 0 && (read = data.read(buf, 0, (int) Math.min(buf.length, remain))) != -1) {
                raf.write(buf, 0, read);
                remain -= read;
            }
        }
    }

    @Override
    public long getOffset(String uploadId) throws IOException {
        Path file = getFilePath(uploadId);
        if (!Files.exists(file)) return 0L;
        return Files.size(file);
    }

    @Override
    public void complete(String uploadId) {
        // 本地实现无特殊处理
    }

    @Override
    public InputStream getInputStream(String uploadId) throws Exception {
        return null;
    }

    @Override
    public long getUploadLength(String uploadId) throws IOException {
        Path meta = getMetaFilePath(uploadId);
        if (!Files.exists(meta)) {
            return -1L;
        }
        try (BufferedReader reader = Files.newBufferedReader(meta)) {
            String s = reader.readLine();
            return Long.parseLong(s);
        }
    }
}
